<html>
<!--
   Licensed to the Apache Software Foundation (ASF) under one or more
   contributor license agreements.  See the NOTICE file distributed with
   this work for additional information regarding copyright ownership.
   The ASF licenses this file to You under the Apache License, Version 2.0
   (the "License"); you may not use this file except in compliance with
   the License.  You may obtain a copy of the License at

       https://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
-->
<head>
<title>Completeness of "Parsing Canonical Form"</title>
</head>
<body>

<center><h1>Completeness of "Parsing Canonical Form"</h1></center>

<h2>1.0 Introduction</h2>

<p>One of the defining characteristics of Avro is that a reader is assumed to have the "same" schema used by the writer of the data the reader is reading.  This assumption leads to a data format that's compact and amenable to many forms of schema evolution.  However, there are nuances to defining exactly what it means for the reader to have "the same" schema used by the writer.  We want to allow, for example, trivial transformations, such as the insertion of whitespace.  But we can't allow transformations that change the real meaning of schemas, such as a reordering of fields in a record</p>

<p>To clearly define what it means for a reader to have "the same" schema as a writer, the Avro specification defines <dfn>Parsing Canonical Form</dfn> (PCF), a set of transformations on Avro schemas that strip away irrelevencies (e.g., "doc" attributes) and normalize the JSON text (e.g., dealing with whitespace).  Two schemas are defined to be "the same" as far as a reader is concerned if and only if their PCFs are textually equal.</p>

<p>We believe that PCF is <em>sound</em> and <em>complete</em>.  Soundness means that the PCF of a schema is logically equivalent to the original form, i.e., we can use the PCF in place of the original form without introducing bugs.  Completeness is "maximal soundness:" if two schemas are logically equivalent, then their PFCs will be textually identical.  The Avro specification claims that PCF is complete when it says: "[if two schemas have the same PCF, then] there is no serialized data that would allow a reader to distinguish data generated by a writer using one of the original schemas from data generated by a writing using the other original schema."</p>

<p>We believe that the transformations that define PCF are "self-evidently" sound to people familiar with Avro.  For example, fixing the order of fields in a JSON object, or eliminating irrelevant attributes like <code>doc</code>, or using the simple <code>int</code> in place of <code>{"type":"int"}</code> clearly don't change the meaning of a schema.</p>

<p>Completeness, on the other hand, is much less obvious.  How do we know that there aren't two logically equivalent schemas that happen to reduce to different canonical forms?  All it takes is one such pair to foil our claim of completeness.</p>

<p>In general, completeness properties like this can be tricky to prove.  It turns out that, while soundness is critical to us, completeness is not.  If two schemas are operationally equivalent (i.e., a reader can't tell their output apart), but we accidentally treat them as if they are different, then typically all that happens is that we'll do more work.  For example, we might generate a decoder object to decode some incoming data when it turns out that we had already cached a decoder object that could do the job.  This is not likely to happen often, and thus incompleteness isn't a huge problem.</p>

<p>At the same time, if we knew that our canonical forms were complete, then we might take advantage of that fact in some circumstances (e.g., to serialize schemas).  Also, the <code>Schema.equals(Object)</code> method provided in the Avro implementation makes many of the same assumptions made in the PCF definition.  Thus, a completeness proof for our canonicalization would give us confidence in the correctness of this equality algorithm.  So this issue is not entirely academic.</p>

<p>We haven't worked out a full, formal proof (we hope someone from the community will step up to that task!).  However, we've been thinking about it quite a bit, and we thought we'd share our thoughts so far.</p>


<h2>2.0 Completeness argument for Parsing Canonical Form</h2>

<p>Our formalization of Avro schemas would be based on interpreting them as grammars.  In this interpretation, Avro schemas are grammars that generate tagged data streams.  Consider, for example, the following schema for a linked-list:
<pre>
  {"type":"record", "name":"list", "fields":[
     {"name":"value", "type":"int"},
     {"name":"tail",  "type":["null", "list"]}
   ]}
</pre>
Interpreted as a grammar, it can generate a tagged data-stream that looks like this:
<pre>
  [record,"list"][field,"value"][int,10][field,"tail"][union,1]
    [record,"list"][field,"value"][int,22][field,"tail"][union,0]
</pre>
(this is a two-record linked list whose first cell contains the value "10" and second cell the value "22").  Avro schemas can trivially be interpreted as grammars for such tagged data streams.  Formal proofs involving Avro schemas can be carried out as proofs about languages and grammars.</p>

<p>So what does it mean for the canonical form of a schema to be "complete?"  Let <i>L(S)</i> denote the language generated by the Avro schema <code>S</code>, and <i>C(S)</i> denote the canonical form of the schema.  The canonicalization is complete if:
<blockquote>
For all schemas <i>S<sub>1</sub></i> and <i>S<sub>2</sub></i>,<br>
&nbsp;&nbsp;&nbsp;&nbsp;<i>L(S<sub>1</sub>) = L(S<sub>2</sub>) &rArr; C(S<sub>1</sub>) = C(S<sub>2</sub>)</i>
</blockquote>
That is, for any two schemas that generate the same language, their canonicalizations are textually equivalent.

<p>To prove this, we need to define some functions:
<blockquote>
<i>J</i> is a variable name we often use to denote a JSON expression representing an Avro schema<br>
<i>C(J)</i> is the Parsing Canonical Form of <i>J</i> as defined in the Avro specification<br>
<i>P(J)</i> is the ASG for an Avro schema generated by parsing <i>J</i> (think of <i>P(J)</i> as a <code>Schema</code> Java object)<br>
<i>S</i> is a variable name we often use to denote such ASGs<br>
<i>L(S)</i> is the language generated by a schema ASG
</blockquote>
<p>With all these symbols defined, our completeness criteria is now rendered as:
<blockquote>
&forall; <i>J<sub>1</sub></i>, <i>J<sub>2</sub></i>:
<i>L(P(J<sub>1</sub>)) = L(P(J<sub>2</sub>)) &rArr; C(J<sub>1</sub>) = C(J<sub>2</sub>)</i>
</blockquote>
We'll prove this by breaking it into two parts:
<blockquote>
(1): &forall; <i>S<sub>1</sub></i>, <i>S<sub>2</sub></i>:
<i>L(S<sub>1</sub>) = L(S<sub>2</sub>) &rArr; S<sub>1</sub> &cong; S<sub>2</sub>  <br>
(2): &forall; <i>J<sub>1</sub></i>, <i>J<sub>2</sub></i>:
<i>P(J<sub>1</sub>) &cong; P(J<sub>2</sub>) &rArr; C(J<sub>1</sub>) = C(J<sub>2</sub>)</i>
</i>
</blockquote>
In this two-step decomposition, we've introduced a new operator &cong;, which compares the ASGs of two Avro schemas.  The ASG of an Avro schema can be viewed as a rooted, labeled, directed graph.  Because Avro schemas can be recursive, these graphs can be cyclic.  The &cong; operator is "true" between two ASGs when the set of minimal labeled paths (no cycles, starting from the root) on the two ASGs are the same.  (The <code>Schema.equals(Object)</code> method in the Avro implementation computes something close to this &cong; relation, except that &cong; ignores "irrelevant" attributes like <code>doc</code> and <code>aliases</code>.)

<p>It turns out that, implicit in the Avro Specification, there are "canonicalization" rules that are important to our proof of completeness.  In particular, the Avro Specification says that a name must be defined "before" it is used, and that a name cannot be defined more than once in a schema.  Consider the following redefinition of the linked-list schema, for example:
<pre>
  {"type":"record", "name":"list", "fields":[
    {"name":"value", "type":"int"},
    {"name":"tail",
      "type":["null", {"type":"record", "name":"list", "fields":[
                        {"name":"value", "type":"int"},
                        {"name":"tail", "type":["null", "list"]}]}]}
  ]}
</pre>
In this redefinition, we've "unpacked" the recursion in the linked list by one level.  In some sense, this is a perfectly fine definition of a linked list, and is operationally equivalent to the more compact version given earlier.  So it makes sense that our claim of completeness is dependent upon this kind of "unpacking" not occuring in real schemas.</p>

<p>To deal with this issue in our proof, we pretend that the Avro specification does <em>not</em> require that named schemas be defined just once, and be defined "before" they are used.  Rather, we treat this requirement as an additional transformation rule in the definition of Parsing Canonical Form:
<ul>
  <li> [MINIMIZE] Eliminate redundant definitions of named types (records, enums, and fixeds).  That is, for each named type, have a defining instance that appears at first use, and then use just the name (rather than the full schema) everywhere else.</li>
</ul>
(As in the Avro spec, "first use" is defined as the first occurrence in a depth-first, left-to-right traversal of the schema abstract-syntax graph (ASG).)

<p>Getting back to the proof of (1) and (2) from above, we need to introduce more functions:
<blockquote>
<i>P(J)=P<sub>A</sub>(P<sub>J</sub>(J))</i> - decompose parser into: <br>
&nbsp;&nbsp;<i>P<sub>J</sub></i> is the JSON parser<br>
&nbsp;&nbsp;<i>P<sub>A</sub></i> is the Avro parser (takes JSON ASTs as input)<br>
<i>C(J)=C<sub>J</sub>(C<sub>A</sub>(C<sub>M</sub>(J)))</i> - decompose canonicalization into:<br>
&nbsp;&nbsp;<i>C<sub>M</sub>(J)</i> the MINIMIZE step<br>
&nbsp;&nbsp;<i>C<sub>A</sub>(J)</i> Avro normalizations<br>
&nbsp;&nbsp;<i>C<sub>J</sub>(J)</i> JSON normalizations<br>
<i>M(S)</i> is the "named-schema NFA minimzation" of <i>S</i><br>
</blockquote>
"Named-schema NFA minimization" is similar to general NFA minimization, except that we only collapse nodes and edges related to named schema entities and not other nodes.  For example, we would <em>not</em> collapse the nodes associated with <code>int</code> or <code>union</code> schemas.

<p> Our proof of (1) looks like this (this proof refers to lemmas (3) and (4), which are defined later):
<blockquote>
<table>
<tr><td>&forall;<i>S<sub>1</sub>,S<sub>2</sub></i>:</td><td><i>L(S<sub>1</sub>)=L(S<sub>2</sub>)</i></td><td></td></tr>
<tr>
<td></td><td>&rArr;<i>M(S<sub>1</sub>)=M(S<sub>2</sub>)</i></td>
<td>by (3)</td>
</tr>
<tr>
<td></td><td>&rArr;<i>S<sub>1</sub>&cong;S<sub>2</sub)</i></td>
<td>by (4)</td>
</tr>
</table>
</blockquote>
Here's the proof of (2) (this proof refers to lemmas (4)-(7), which are defined later):
<blockquote>
<table>
<tr><td>&forall;<i>J<sub>1</sub>,J<sub>2</sub></i>:</td><td><i>P(J<sub>1</sub>)&cong;P(J<sub>2</sub>)</i></td><td></td></tr>

<tr>
<td></td><td>&rArr;<i>M(P(J<sub>1</sub>))=M(P(J<sub>2</sub>))</i></td>
<td>by (4)</td>
</tr>

<tr>
<td></td><td>&rArr;<i>P(C<sub>M</sub>(J<sub>1</sub>))=P(C<sub>M</sub>(J<sub>2</sub>))</i></td>
<td>by (5)</td>
</tr>

<tr>
<td></td><td>&rArr;<i>P<sub>A</sub>(P<sub>J</sub>(C<sub>M</sub>(J<sub>1</sub>)))=P<sub>A</sub>(P<sub>J</sub>(C<sub>M</sub>(J<sub>2</sub>)))</i></td>
<td>by definition of <i>P</i></td>
</tr>

<tr>
<td></td><td>&rArr;<i>P<sub>J</sub>(C<sub>A</sub>(C<sub>M</sub>(J<sub>1</sub>)))=P<sub>J</sub>(C<sub>A</sub>(C<sub>M</sub>(J<sub>2</sub>)))</i></td>
<td>by (6)</td>
</tr>

<tr>
<td></td><td>&rArr;<i>C<sub>J</sub>(C<sub>A</sub>(C<sub>M</sub>(J<sub>1</sub>)))=C<sub>J</sub>(C<sub>A</sub>(C<sub>M</sub>(J<sub>2</sub>)))</i></td>
<td>by (7)</td>
</tr>

<tr>
<td></td><td>&rArr;<i>C(J<sub>1</sub>)=C(J<sub>2</sub>)</i></td>
<td>by definition of <i>C</i></td>
</tr>
</table>
</blockquote>

Here are the lemmas needed above:
<blockquote>
(3): &forall; <i>S<sub>1</sub></i>, <i>S<sub>2</sub></i>:
<i>L(S<sub>1</sub>) = L(S<sub>2</sub>) &rArr; M(S<sub>1</sub>) = M(S<sub>2</sub>)</i><br>

(4): &forall; <i>S<sub>1</sub></i>, <i>S<sub>2</sub></i>:
<i>M(S<sub>1</sub>) = M(S<sub>2</sub>) &hArr; S<sub>1</sub> &cong; S<sub>2</sub></i> <br>

(5): &forall; <i>J</i>: <i>M(P(J)) = P(C<sub>M</sub>(J))</i><br>

(6): &forall; <i>J<sub>1</sub></i>, <i>J<sub>2</sub></i>:
<i>P<sub>A</sub>(P<sub>J</sub>(J<sub>1</sub>)) = P<sub>A</sub>(P<sub>J</sub>(J<sub>2</sub>)) &rArr; P<sub>J</sub>(C<sub>A</sub>(J<sub>1</sub>)) = P<sub>J</sub>(C<sub>A</sub>(J<sub>2</sub>))</i> <br>

(7): &forall; <i>J<sub>1</sub></i>, <i>J<sub>2</sub></i>:
<i>P<sub>J</sub>(J<sub>1</sub>) = P<sub>J</sub>(J<sub>2</sub>) &rArr; C<sub>J</sub>(J<sub>1</sub>) = C<sub>J</sub>(J<sub>2</sub>)</i> <br>
</blockquote>

<p>Proving the lemmas:
<ol start="3">
<li> This says that the language-related part of our canonicalization is complete, i.e., <i>M</i> finds the equivalence-classes of <i>L</i>.  I would imagine one could prove this by modifying a proof that the equality of LL(1) grammars is a decidable problem.  I haven't gotten very far in showing this, however.
<li> The right-hand direction of this follows from the definition of minimization.  The left-hand direction seems correct, but I'm not sure how to prove it (I think it also follows from the definition of minimization).
<li> This is showing that the MINIMIZE step (which is done on JSON expressions) is equivalent to doing an named-schema NFA minimization on the ASG representation.  This should follow pretty directly from a detailed definition of <i>M</i>, if we provided one.
<li> This says that the Avro-related part of our canonicalization is complete, i.e., that <i>C<sub>A</sub></i> finds equivalence-classes of <i>P<sub>A</sub></i>.
<li> This says that the JSON-related part of our canonicalization is complete, i.e., that <i>C<sub>J</sub></i> finds equivalence-classes of <i>P<sub>J</sub></i>.  Note that, implicitly, this lemma ranges over only JSON expressions that are legal Avro schemas with no doc strings or default values, and thus (for example) doesn't need to worry about normalization of floating-point literals.
</ol>


<h2>3.0 Concluding remarks</h2>

Engineers <a href="https://www.aps.org/publications/apsnews/201002/physicshistory.cfm">have a history</a> of running ahead of formal mathematical proofs, when things "seem correct" to them.  In this case, it seems pretty obvious that Parsing Canonical Form is complete as well as sound, and we should go ahead and treat it as such.  At the same time, formal proofs often turn up corner cases and exceptions that are valuable to document and account for.  Thus, it'd nice if someone could provide a better completeness argument than we've been able to so far.

</body>
</html>
